﻿using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Jungle.Code.Utils;
using Jungle.Code.DAL;
using Jungle.Code.BLL;
using Jungle.Code.Core;
using Jungle.Modules;

using Jungle.Rent;
using Jungle.Users;
using Jungle.Code.Core;

    public partial class NodeMenu_Admin : BaseAdminModule
    {
        private int LangId = 1;
        // ----------------------------------------------------------------------------
        protected override void OnInit(EventArgs e)
        {
            SessionKeeper sk = new SessionKeeper();
            sk.SessionId = Session.SessionID;
            sk.GetData();

            UserManager user = new UserManager();
            user.UserId = sk.UserId;
            user.GetById();

            HttpCookie cookie = Request.Cookies["CurrLang"];
            if (cookie != null) LangId = Convert.ToInt32(cookie["lang"]);

            Admin_ItemList1.LangId = LangId;

            btn_OpenAddItem.PostBackUrl = Request.RawUrl;
            LoadDdls();
            switch (Request["cmd"])
            { 
                case "add":
                    GlobalMenu.ActiveViewIndex = 0;
                    if (Request["pid"] != null) ddl_Parrents.Items.FindByValue(Request["pid"]).Selected = true;
                    break;
                case "edit":
                    GlobalMenu.ActiveViewIndex = 0;
                    btn_Edit.Visible = true;
                    btn_Add.Visible = false;
                    LoadDataForEdit();
                    break;
                default:
                    GlobalMenu.ActiveViewIndex = 1;
                    break;
            }
          
            base.OnInit(e);
        }
        // ----------------------------------------------------------------------------
        protected void LoadDdls()
        {
            StreamReader reader = new StreamReader(Server.MapPath("/Modules/NodeMenu/option.xml"));
            XmlDocument optionFile = new XmlDocument();
            optionFile.LoadXml(reader.ReadToEnd());
            reader.Close();

            XmlNode nodeMtype = optionFile.ChildNodes[1].ChildNodes[0];
            ddl_mType.Items.FindByValue(nodeMtype.InnerText.Trim()).Selected = true;

            ddl_Nodes.Items.Clear();
            Node TopNode = new Node();
            TopNode = Node.GetTopByLangID(LangId);
            ddl_Nodes.Items.Add(new ListItem(TopNode.Name, TopNode.NodeID.ToString()));
            BuilTree(TopNode.NodeID, 0);

            List<NodeMenu> roots = NodeMenu.GetRoots(LangId);
            foreach (NodeMenu r in roots)
            {
                ddl_Parrents.Items.Add(new ListItem("..." + r.Title, r.ItemId.ToString()));
                AddByParrent(r.ItemId, "...");
            }
        }
        // ----------------------------------------------------------------------------
        private void BuilTree(int parrentId, int level)
        {
            List<Node> nodes = Node.GetByParentNodeID(parrentId);
            string prest = ""; for (int i = 0; i <= level; i++) { prest += "..."; }

                foreach (Node n in nodes)
                {
                    ddl_Nodes.Items.Add(new ListItem(prest + n.Name, n.NodeID.ToString()));
                    BuilTree(n.NodeID, level + 1);
                }
        }
        // ----------------------------------------------------------------------------
        private void AddByParrent(int ParrentId, string level)
        {
            List<NodeMenu> childs = NodeMenu.GetByParrent(ParrentId);
            foreach (NodeMenu c in childs)
            {
                ddl_Parrents.Items.Add(new ListItem(level + c.Title, c.ItemId.ToString()));
                AddByParrent(c.ItemId, level += "...");
            }
            
        }
        // ----------------------------------------------------------------------------
        public void LoadDataForEdit()
        {
            if (Request["id"] != null)
            {
                NodeMenu n = NodeMenu.GetById(Convert.ToInt32(Request["id"]));
                ddl_Nodes.Items.FindByValue(n.NodeId.ToString()).Selected = true;
                tb_Title.Text = n.Title;
                chb_IsActive.Checked = n.IsActive;
                ddl_Parrents.Items.FindByValue(n.ParrentItemId.ToString()).Selected = true;
            }
        }
        // ----------------------------------------------------------------------------
        public void OpenAddItem(object sender, EventArgs e)
        { 
           Response.Redirect("Modules.aspx?mod=NodeMenu&cmd=add&pid=0");
        }
        // ----------------------------------------------------------------------------
        public void AddItem(object sender, EventArgs e)
        {
            try
            {
                NodeMenu newItem = new NodeMenu();
                newItem.NodeId = Convert.ToInt32(ddl_Nodes.SelectedValue);
                newItem.Title = tb_Title.Text.Trim();
                newItem.OrderInt = 0;
                newItem.IsActive = chb_IsActive.Checked;
                newItem.ParrentItemId = Convert.ToInt32(ddl_Parrents.SelectedValue);

                newItem.Add();
                Response.Redirect("Modules.aspx?mod=NodeMenu&cmd=default");
            }
            catch(Exception ex)
            {
                lb_error.Text = "Произошла ошибка" + ex.Message;
            }

            
        }
        // ----------------------------------------------------------------------------
        public void Chanchge_mType(object sender, EventArgs e)
        {
            StreamReader reader = new StreamReader(Server.MapPath("/Modules/NodeMenu/option.xml"));
            string allFile = reader.ReadToEnd();
            if (ddl_mType.SelectedValue == "Horizont") allFile = allFile.Replace("Vertical", "Horizont");
            if (ddl_mType.SelectedValue == "Vertical") allFile = allFile.Replace("Horizont", "Vertical");
            reader.Close();

            StreamWriter wr = new StreamWriter(Server.MapPath("/Modules/NodeMenu/option.xml"), false);
            wr.Write(allFile);
            wr.Close();

        }
        // ----------------------------------------------------------------------------
        public void EditItem(object sender, EventArgs e)
        {
            try
            {
                NodeMenu n = NodeMenu.GetById(Convert.ToInt32(Request["id"]));
                n.NodeId = Convert.ToInt32(ddl_Nodes.SelectedValue);
                n.Title = tb_Title.Text.Trim();
                n.IsActive = chb_IsActive.Checked;
                n.ParrentItemId = Convert.ToInt32(ddl_Parrents.SelectedValue);

                n.Update();
                Response.Redirect("Modules.aspx?mod=NodeMenu&cmd=default");
            }
            catch(Exception ex)
            {
                lb_error.Text = "Произошла ошибка" + ex.Message;
            }

            
        }
        // ----------------------------------------------------------------------------
        public override void FillBaseInfo()
        {
            sysName = "NodeMenu";
        }
        // ----------------------------------------------------------------------------
        public override void Main()
        {
        }       
    }
